package com.zim.aliot.service.impl;

import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.zim.aliot.service.RestService;

@Service
public class RestServiceImpl implements RestService {
    
    private final RestTemplate restTemplate;
    
    public RestServiceImpl(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }
    
    public RestTemplate getRestTemplate() {
        return restTemplate;
    }
    
    @Override
    public <T> ResponseEntity<T> requestLai(String url, Class<T> request,ParameterizedTypeReference<T> responseType) {
        
        return restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(request,jsonHeaders()), responseType);
        
    }
    
    public HttpHeaders jsonHeaders(MultiValueMap<String, String> values) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        
        headers.addAll(values);
        
        return headers;
    }
    
    public HttpHeaders jsonHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

}
